package com.agger.harmonyosthemeseditor.abilities.slices;

import com.agger.harmonyosthemeseditor.ResourceTable;
import com.agger.harmonyosthemeseditor.ThemesEditorAbility;
import com.agger.harmonyosthemeseditor.abilities.PreloadServiceAbility;
import com.agger.harmonyosthemeseditor.intelligent.*;
import com.agger.harmonyosthemeseditor.userinterface.*;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.colors.HsvColor;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.*;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.Color;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.CommonDialog;
import ohos.agp.window.dialog.PopupDialog;
import ohos.agp.window.service.DisplayAttributes;
import ohos.agp.window.service.DisplayManager;
import ohos.agp.window.service.WindowManager;
import ohos.bundle.AbilityInfo;
import ohos.bundle.IBundleManager;
import ohos.data.rdb.ValuesBucket;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.eventhandler.InnerEvent;
import ohos.global.resource.ResourceManager;
import ohos.media.common.Source;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.photokit.metadata.AVMetadataHelper;
import ohos.media.photokit.metadata.AVStorage;
import ohos.media.player.Player;
import ohos.os.ProcessManager;
import ohos.utils.IntentConstants;
import ohos.utils.net.Uri;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;

public class SpeedUpThemeSlice extends AbilitySlice
{
    private final int ChooseImage_Background = 1003;
    private final int ChooseImage_Desktop = 1004;
    private final int ChooseImage_Unlock = 1005;
    private final int ChooseImage_Desktop_byCamera = 303;
    private final int ChooseImage_Unlock_byCamera = 306;
    private final int ChooseVideo = 1002;
    Image showImageArea = null;
    PixelMap pxm = null;
    TextField textBox_ChineseName = null;
    TextField textBox_InternationalName = null;
    TextField textBox_DesignerName = null;
    TextField textBox_VersionCode = null;
    TextField textBox_BriefInfo = null;
    Component text_ChineseName = null;
    Component text_InternationalName = null;
    Component text_DesignerName = null;
    Component text_VersionCode = null;
    String Dialog_Title = "爱洁羊智慧能力";
    String Dialog_Content_StoragePermissionFailed = "存储功能被禁用，请前往应用管理页，开启主题协作器的存储权限！";
    String Dialog_Content_CameraPermissionFailed = "相机功能被禁用，请前往应用管理页，开启主题协作器的相机权限！";
    String Dialog_Button_Cancel = "取消";
    String Dialog_Button_Confirm = "好的";
    String Toast_NoneName = "请录入主题包名称！汉语名称、国际名称，至少填写一项！";
    String Toast_NoneDesigner = "请录入主题包的设计师名称！";
    String Toast_NoneVersion = "请录入主题包的版本号码！";
    String Toast_NoneBriefInfo = "请录入主题包的简单介绍信息！";
    String Toast_NoneDesktop = "请选取桌面壁纸图！";
    String Toast_NoneUnlock = "请选取锁屏壁纸图！";
    String Toast_NoneBackground = "请先选取软件背景图！";
    String Toast_IsProcessing = "主题生成中，请勿进行其它操作！";
    String Toast_Theme_SaveFinish = "主题包已存储至";
    String Toast_Theme_SaveFailed = "存储主题包时出现错误，请确保设备容量充足！";
    MainThreadEventHandler mainThreadEventHandler;
    PacThemeEventHandler PacThemeEventHandler;
    ScreenEventHandler screenEventHandler;
    Text text_ColorSelector = null;
    Text text_DesktopSelector = null;
    Text text_UnlockSelector = null;
    Text text_CardRadius = null;
    Slider RadiusSlider = null;
    String Color01 = "FFC6B7";
    String Color02 = "FCE4DE";
    String Color03 = "F4C4B7";
    String Color04 = "FF8362";
    String Color05 = "FFC1B0";
    String Color06 = "996D61";
    String Color07 = "FF8362";
    String Color08 = "FCD8CF";
    String Color09 = "FFF4F2";
    String Color10 = "F4EDEB";
    String Color11 = "EA791A";
    String Color12 = "CCFFF6F4";
    String Color13 = "E17618";
    String Color14 = "FFEEEA";
    String Color15 = "FCDCD4";
    String Color16 = "FFF2EF";
    String Color17 = "FCDED6";
    String Color18 = "FFDCD3";
    String Color19 = "E2907A";
    boolean isProcessing = false;
    boolean isSuccess = false;
    boolean BigSuccess = false;
    ColorDialog colorDialog = null;
    String ThemesDate = "20220222022022";
    PopupDialog imageSelector_Popup = null;

    @Override
    protected void onOrientationChanged(AbilityInfo.DisplayOrientation displayOrientation)
    {
        super.onOrientationChanged(displayOrientation);
        try
        {
            if(!colorDialog.isDestroyed)
            {
                if(!colorDialog.isShowing())
                {
                    colorDialog.setDestroyedListener(null);
                    colorDialog.destory();
                    colorDialog = null;
                    System.gc();
                }
                else
                {
                    colorDialog.setDestroyedListener(null);
                    colorDialog.saveTempColorValue();
                    colorDialog.destory();
                    colorDialog = null;
                    System.gc();
                    recoverDialog_ColorSelector();
                }
            }
        }catch (Exception ex){}
        try
        {
            imageSelector_Popup.destroy();
            imageSelector_Popup = null;
        }catch (Exception ex){}
        try
        {
            DisplayAttributes displayAttributes = DisplayManager.getInstance().getDefaultDisplay(this).get().getAttributes();
            int maxTextWidth = displayAttributes.width-(int)(216f*displayAttributes.scalDensity+0.5f);
            text_ChineseName.setLayoutRefreshedListener(null);
            text_InternationalName.setLayoutRefreshedListener(null);
            text_DesignerName.setLayoutRefreshedListener(null);
            text_VersionCode.setLayoutRefreshedListener(null);
            text_ChineseName.setWidth(ComponentContainer.LayoutConfig.MATCH_CONTENT);
            text_InternationalName.setWidth(ComponentContainer.LayoutConfig.MATCH_CONTENT);
            text_DesignerName.setWidth(ComponentContainer.LayoutConfig.MATCH_CONTENT);
            text_VersionCode.setWidth(ComponentContainer.LayoutConfig.MATCH_CONTENT);
            text_ChineseName.setLayoutRefreshedListener(c->{if(c.getWidth()>maxTextWidth)c.setWidth(maxTextWidth);});
            text_InternationalName.setLayoutRefreshedListener(c->{if(c.getWidth()>maxTextWidth)c.setWidth(maxTextWidth);});
            text_DesignerName.setLayoutRefreshedListener(c->{if(c.getWidth()>maxTextWidth)c.setWidth(maxTextWidth);});
            text_VersionCode.setLayoutRefreshedListener(c->{if(c.getWidth()>maxTextWidth)c.setWidth(maxTextWidth);});
        }catch (Exception e){}
    }

    private class PacThemeEventHandler extends EventHandler
    {
        private PacThemeEventHandler(EventRunner runner) {
            super(runner);
        }
        @Override
        public void processEvent(InnerEvent event)
        {
            super.processEvent(event);
            if (event == null)
            {
                return;
            }
            isSuccess = false;
            BigSuccess = false;
            ProcessManager.setThreadPriority(-20);
            String workPath = getCacheDir() + "/SpeedUpThemeArea";
            File WorkStorage = new File(workPath);
            if(WorkStorage.exists())FileManager.deleteDirectory(workPath,true,false);
            new File(workPath+"/wallpaper").mkdirs();
            FileManager.copyFile(getCacheDir() + "/SpeedUpTheme/Desktop.jpg",workPath+"/wallpaper/home_wallpaper_0.jpg");
            FileManager.copyFile(getCacheDir() + "/SpeedUpTheme/Unlock.jpg",workPath+"/wallpaper/unlock_wallpaper_0.jpg");
            new File(workPath+"/preview").mkdirs();
            FileManager.copyDir(getFilesDir()+"/ThemesTemplate/unlock_slide",workPath+"/unlock");
            FileManager.copyFile(getFilesDir()+"/ThemesTemplate/preview/preview_icons_0.jpg",workPath+"/preview/preview_icons_0.jpg");
            PixelMap unlockImage = GeneralUtil.getPixelMapFromFile(new File(getCacheDir() + "/SpeedUpTheme/Unlock.jpg"));
            if(unlockImage!=null)
            ImageIntelligent.saveImage(workPath+"/preview/cover.jpg",ImageIntelligent.ResizeImage(unlockImage,1080,2160));
            FileManager.copyFile(workPath+"/preview/cover.jpg",workPath+"/preview/preview_unlock_0.jpg");
            FileManager.copyFile(getFilesDir()+"/ThemesTemplate/icons",workPath+"/icons");
            FileManager.copyFile(getFilesDir()+"/ThemesTemplate/description.xml",workPath+"/description.xml");
            File xmlFile = new File(workPath+"/description.xml");
            try
            {
                FileInputStream in = new FileInputStream(xmlFile);
                byte[] b = new byte[(int) xmlFile.length()];
                in.read(b);
                String xmlText = new String(b);
                in.close();
                xmlText = xmlText.replaceAll("汉语名称",textBox_ChineseName.getText());
                xmlText = xmlText.replaceAll("国际名称",textBox_InternationalName.getText());
                xmlText = xmlText.replaceAll("设计师名",textBox_DesignerName.getText());
                xmlText = xmlText.replaceAll("版本号码",textBox_VersionCode.getText());
                xmlText = xmlText.replaceAll("简介信息",textBox_BriefInfo.getText());
                FileOutputStream out = null;
                try
                {
                    out = new FileOutputStream(xmlFile);
                    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, StandardCharsets.UTF_8));
                    writer.write(xmlText);
                    writer.close();
                    out.flush();
                    out.close();
                }catch(IOException ex){ex.printStackTrace();}
                finally
                {
                    try
                    {
                        if (out != null)
                        {
                            out.close();
                        }
                    } catch(IOException e){}
                }
            }catch(IOException ex) {}
            if(!new File(getCacheDir() + "/SpeedUpTheme/Background.jpg").exists())
                ImageIntelligent.saveImage(getCacheDir() + "/SpeedUpTheme/Background.jpg",showImageArea.getPixelMap());
            if(new File(getCacheDir()+"/SpeedUpTheme/com.android.contacts").exists())
                FileManager.deleteDirectory(getCacheDir()+"/SpeedUpTheme/com.android.contacts",true,false);
            if(new File(getCacheDir()+"/SpeedUpTheme/com.android.incallui").exists())
                FileManager.deleteDirectory(getCacheDir()+"/SpeedUpTheme/com.android.incallui",true,false);
            if(new File(getCacheDir()+"/SpeedUpTheme/com.android.mms").exists())
                FileManager.deleteDirectory(getCacheDir()+"/SpeedUpTheme/com.android.mms",true,false);
            if(new File(getCacheDir()+"/SpeedUpTheme/com.android.phone").exists())
                FileManager.deleteDirectory(getCacheDir()+"/SpeedUpTheme/com.android.phone",true,false);
            if(new File(getCacheDir()+"/SpeedUpTheme/com.android.systemui").exists())
                FileManager.deleteDirectory(getCacheDir()+"/SpeedUpTheme/com.android.systemui",true,false);
            if(new File(getCacheDir()+"/SpeedUpTheme/com.huawei.android.launcher").exists())
                FileManager.deleteDirectory(getCacheDir()+"/SpeedUpTheme/com.huawei.android.launcher",true,false);
            if(new File(getCacheDir()+"/SpeedUpTheme/com.huawei.ohos.famanager").exists())
                FileManager.deleteDirectory(getCacheDir()+"/SpeedUpTheme/com.huawei.ohos.famanager",true,false);
            FileManager.copyDir(getFilesDir()+"/ThemesTemplate/contacts",getCacheDir()+"/SpeedUpTheme/com.android.contacts");
            FileManager.copyDir(getFilesDir()+"/ThemesTemplate/framework",getCacheDir()+"/SpeedUpTheme/com.android.contacts/framework-res-hwext");
            FileManager.copyFile(getCacheDir()+"/SpeedUpTheme/Background.jpg",getCacheDir()+"/SpeedUpTheme/com.android.contacts/framework-res-hwext/res/drawable-xxhdpi/background_emui.9.png");
            updateXmlColorValue(getCacheDir()+"/SpeedUpTheme/com.android.contacts/framework-res-hwext/theme.xml");
            updateXmlColorValue(getCacheDir()+"/SpeedUpTheme/com.android.contacts/theme.xml");
            try{ZipFileManager.zip(getCacheDir()+"/SpeedUpTheme/com.android.contacts",workPath+"/com.android.contacts");}catch(Exception e){}
            FileManager.copyDir(getFilesDir()+"/ThemesTemplate/incallui",getCacheDir()+"/SpeedUpTheme/com.android.incallui");
            try{ZipFileManager.zip(getCacheDir()+"/SpeedUpTheme/com.android.incallui",workPath+"/com.android.incallui");}catch(Exception e){}
            FileManager.copyDir(getFilesDir()+"/ThemesTemplate/mms",getCacheDir()+"/SpeedUpTheme/com.android.mms");
            FileManager.copyDir(getFilesDir()+"/ThemesTemplate/framework",getCacheDir()+"/SpeedUpTheme/com.android.mms/framework-res-hwext");
            FileManager.copyFile(getCacheDir()+"/SpeedUpTheme/Background.jpg",getCacheDir()+"/SpeedUpTheme/com.android.mms/framework-res-hwext/res/drawable-xxhdpi/background_emui.9.png");
            FileManager.copyFile(getCacheDir()+"/SpeedUpTheme/com.android.contacts/framework-res-hwext/theme.xml",getCacheDir()+"/SpeedUpTheme/com.android.mms/framework-res-hwext/theme.xml");
            updateXmlColorValue(getCacheDir()+"/SpeedUpTheme/com.android.mms/theme.xml");
            try{ZipFileManager.zip(getCacheDir()+"/SpeedUpTheme/com.android.mms",workPath+"/com.android.mms");}catch(Exception e){}
            new File(getCacheDir()+"/SpeedUpTheme/com.android.phone").mkdirs();
            FileManager.copyDir(getFilesDir()+"/ThemesTemplate/framework",getCacheDir()+"/SpeedUpTheme/com.android.phone/framework-res-hwext");
            FileManager.copyFile(getCacheDir()+"/SpeedUpTheme/Background.jpg",getCacheDir()+"/SpeedUpTheme/com.android.phone/framework-res-hwext/res/drawable-xxhdpi/background_emui.9.png");
            FileManager.copyFile(getCacheDir()+"/SpeedUpTheme/com.android.contacts/framework-res-hwext/theme.xml",getCacheDir()+"/SpeedUpTheme/com.android.phone/framework-res-hwext/theme.xml");
            try{ZipFileManager.zip(getCacheDir()+"/SpeedUpTheme/com.android.phone",workPath+"/com.android.phone");}catch(Exception e){}
            if(new File(workPath+"/com.android.phone").exists())FileManager.copyFile(workPath+"/com.android.phone",workPath+"/com.android.server.telecom");
            else try{ZipFileManager.zip(getCacheDir()+"/SpeedUpTheme/com.android.phone",workPath+"/com.android.server.telecom");}catch(Exception e){}
            if(new File(workPath+"/com.android.phone").exists())FileManager.copyFile(workPath+"/com.android.phone",workPath+"/com.huawei.phone.recorder");
            else try{ZipFileManager.zip(getCacheDir()+"/SpeedUpTheme/com.android.phone",workPath+"/com.huawei.phone.recorder");}catch(Exception e){}
            FileManager.copyDir(getFilesDir()+"/ThemesTemplate/mediacontroller",getCacheDir()+"/SpeedUpTheme/com.android.systemui");
            FileManager.copyDir(getFilesDir()+"/ThemesTemplate/framework",getCacheDir()+"/SpeedUpTheme/com.android.systemui/framework-res-hwext");
            FileManager.copyFile(getCacheDir()+"/SpeedUpTheme/Background.jpg",getCacheDir()+"/SpeedUpTheme/com.android.systemui/framework-res-hwext/res/drawable-xxhdpi/background_emui.9.png");
            FileManager.copyFile(getCacheDir()+"/SpeedUpTheme/com.android.contacts/framework-res-hwext/theme.xml",getCacheDir()+"/SpeedUpTheme/com.android.systemui/framework-res-hwext/theme.xml");
            updateXmlColorValue(getCacheDir()+"/SpeedUpTheme/com.android.systemui/theme.xml");
            try{ZipFileManager.zip(getCacheDir()+"/SpeedUpTheme/com.android.systemui",workPath+"/com.android.systemui");}catch(Exception e){}
            if(new File(workPath+"/com.android.systemui").exists())FileManager.copyFile(workPath+"/com.android.systemui",workPath+"/com.huawei.mediacontroller");
            else try{ZipFileManager.zip(getCacheDir()+"/SpeedUpTheme/com.android.systemui",workPath+"/com.huawei.mediacontroller");}catch(Exception e){}
            FileManager.copyDir(getFilesDir()+"/ThemesTemplate/launcher",getCacheDir()+"/SpeedUpTheme/com.huawei.android.launcher");
            FileManager.copyDir(getFilesDir()+"/ThemesTemplate/framework",getCacheDir()+"/SpeedUpTheme/com.huawei.android.launcher/framework-res-hwext");
            FileManager.copyDir(getFilesDir()+"/ThemesTemplate/card/framework-res-hwext",getCacheDir()+"/SpeedUpTheme/com.huawei.android.launcher/framework-res-hwext");
            FileManager.copyFile(getCacheDir()+"/SpeedUpTheme/Background.jpg",getCacheDir()+"/SpeedUpTheme/com.huawei.android.launcher/framework-res-hwext/res/drawable-xxhdpi/background_emui.9.png");
            FileManager.copyFile(getCacheDir()+"/SpeedUpTheme/com.android.contacts/framework-res-hwext/theme.xml",getCacheDir()+"/SpeedUpTheme/com.huawei.android.launcher/framework-res-hwext/theme.xml");
            updateXmlColorValue(getCacheDir()+"/SpeedUpTheme/com.huawei.android.launcher/theme.xml");
            updateXmlRadiusValue(getCacheDir()+"/SpeedUpTheme/com.huawei.android.launcher/framework-res-hwext/res/values/dimens.xml");
            try{ZipFileManager.zip(getCacheDir()+"/SpeedUpTheme/com.huawei.android.launcher",workPath+"/com.huawei.android.launcher");}catch(Exception e){}
            new File(getCacheDir()+"/SpeedUpTheme/com.huawei.ohos.famanager").mkdirs();
            FileManager.copyDir(getFilesDir()+"/ThemesTemplate/card/framework-res-hwext",getCacheDir()+"/SpeedUpTheme/com.huawei.ohos.famanager/framework-res-hwext");
            FileManager.copyFile(getCacheDir()+"/SpeedUpTheme/com.huawei.android.launcher/framework-res-hwext/res/values/dimens.xml",getCacheDir()+"/SpeedUpTheme/com.huawei.ohos.famanager/framework-res-hwext/res/values/dimens.xml");
            try{ZipFileManager.zip(getCacheDir()+"/SpeedUpTheme/com.huawei.ohos.famanager",workPath+"/com.huawei.ohos.famanager");}catch(Exception e){}
            if(new File(workPath+"/com.huawei.ohos.famanager").exists())FileManager.copyFile(workPath+"/com.huawei.ohos.famanager",workPath+"/com.huawei.ohos.search");
            else try{ZipFileManager.zip(getCacheDir()+"/SpeedUpTheme/com.huawei.ohos.famanager",workPath+"/com.huawei.ohos.search");}catch(Exception e){}
            try
            {
                if(!new File(getCacheDir()+"/Project_Themes").exists()) new File(getCacheDir()+"/Project_Themes").mkdirs();
                ZipFileManager.zip(workPath,getCacheDir()+"/Project_Themes/"+textBox_InternationalName.getText()+".hwt");
                InputStream input = null;
                try
                {
                    input = new FileInputStream(getCacheDir()+"/Project_Themes/"+textBox_InternationalName.getText()+".hwt");
                    ValuesBucket valuesBucket = new ValuesBucket();
                    valuesBucket.putString(AVStorage.Downloads.DISPLAY_NAME, textBox_InternationalName.getText()+".hwt");
                    valuesBucket.putString("relative_path", "Download/ThemesEditor/");
                    valuesBucket.putInteger("is_pending", 1);
                    DataAbilityHelper helper = GeneralUtil.createDataAbilityHelper(getContext());
                    int id = helper.insert(AVStorage.Downloads.EXTERNAL_DATA_ABILITY_URI, valuesBucket);
                    Uri uri = Uri.appendEncodedPathToUri(AVStorage.Downloads.EXTERNAL_DATA_ABILITY_URI, String.valueOf(id));
                    FileDescriptor fd = helper.openFile(uri, "w");
                    OutputStream output= new FileOutputStream(fd);
                    byte[] buf = new byte[1024];
                    int bytesRead;
                    while ((bytesRead = input.read(buf)) > 0)
                    {
                        output.write(buf, 0, bytesRead);
                    }
                    output.flush();
                    output.close();
                    valuesBucket.clear();
                    valuesBucket.putInteger("is_pending", 0);
                    helper.update(uri, valuesBucket, null);
                    isSuccess = true;
                    ThemesDate = GeneralUtil.getTimeStr();
                    //部分机型未限制存储分区，可直接将主题包复制到/Huawei/Themes目录
                    Files.copy(new File(getCacheDir()+"/Project_Themes/"+textBox_InternationalName.getText()+".hwt").toPath(),new File("/storage/emulated/0/Huawei/Themes/"+ThemesDate+".hwt").toPath(), StandardCopyOption.REPLACE_EXISTING);
                    BigSuccess = true;
                }catch (Exception ex) {}
                finally {input.close();}
            }catch (Exception e){e.printStackTrace();}
            mainThreadEventHandler.sendEvent(0,0,EventHandler.Priority.IMMEDIATE);
        }
    }

    private class MainThreadEventHandler extends EventHandler
    {
        private MainThreadEventHandler(EventRunner runner) {
            super(runner);
        }
        @Override
        public void processEvent(InnerEvent event)
        {
            super.processEvent(event);
            if (event == null)
            {
                return;
            }
            if(BigSuccess)
            {
                new GeneralToast(getContext())
                        .setText(Toast_Theme_SaveFinish+"Huawei/Themes/"+ThemesDate+".hwt")
                        .show();
            }else
            {
                new GeneralToast(getContext())
                        .setText(isSuccess?(Toast_Theme_SaveFinish+"Download/ThemesEditor/"+textBox_InternationalName.getText()+".hwt"):Toast_Theme_SaveFailed)
                        .show();
            }
            isProcessing = false;
            textBox_ChineseName.setEnabled(true);
            textBox_InternationalName.setEnabled(true);
            textBox_DesignerName.setEnabled(true);
            textBox_VersionCode.setEnabled(true);
            textBox_BriefInfo.setEnabled(true);
            RadiusSlider.setEnabled(true);
            textBox_ChineseName.setClickedListener(null);
            textBox_InternationalName.setClickedListener(null);
            textBox_DesignerName.setClickedListener(null);
            textBox_VersionCode.setClickedListener(null);
            textBox_BriefInfo.setClickedListener(null);
            screenEventHandler.sendSyncEvent(0,EventHandler.Priority.IMMEDIATE);
        }
    }

    private class ScreenEventHandler extends EventHandler
    {
        private ScreenEventHandler(EventRunner runner) {
            super(runner);
        }
        @Override
        public void processEvent(InnerEvent event)
        {
            super.processEvent(event);
            if(event == null) return;
            if(event.eventId == 0) {try{getWindow().clearFlags(WindowManager.LayoutConfig.MARK_SCREEN_ON_ALWAYS);}catch (Exception e){}}
            else {try{getWindow().addFlags(WindowManager.LayoutConfig.MARK_SCREEN_ON_ALWAYS);}catch (Exception e){}}
        }
    }

    @Override
    public void onStart(Intent intent)
    {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_slice_speedup_themes);
        this.getWindow().setStatusBarColor(ResourceTool.getColor(this,ResourceTable.Color_dawnlighti_statusbar_normal,0xF7EDD8));
        this.getWindow().setNavigationBarColor(ResourceTool.getColor(this,ResourceTable.Color_dawnlighti_navigationbar_normal,0xF7EDD8));
        int CurrentColorMode = getColorMode();
        if(CurrentColorMode == 0) this.getWindow().setStatusBarVisibility(0);
        else if(CurrentColorMode == 1) this.getWindow().setStatusBarVisibility(2052);
        this.getWindow().setBackgroundColor(RgbColor.fromArgbInt(ResourceTool.getColor(this,ResourceTable.Color_dawnlighti_statusbar_normal,0xFEEFF4)));
        ThemesEditorAbility.Instance.eventRunner = EventRunner.current();
        mainThreadEventHandler = new MainThreadEventHandler(EventRunner.current());
        screenEventHandler = new ScreenEventHandler(EventRunner.current());
        GeneralUtil.setWindowToMaxRefreshRate(getWindow());
        GeneralUtil.setWindowSoftInputMode(getWindow(),GeneralUtil.SOFT_INPUT_ADJUST_PAN);
        try
        {
            if (verifySelfPermission("ohos.permission.READ_USER_STORAGE") != IBundleManager.PERMISSION_GRANTED || verifySelfPermission("ohos.permission.WRITE_USER_STORAGE") != IBundleManager.PERMISSION_GRANTED)
            {
                if (canRequestPermission("ohos.permission.READ_USER_STORAGE")&&canRequestPermission("ohos.permission.WRITE_USER_STORAGE"))
                    requestPermissionsFromUser(new String[] { "ohos.permission.READ_USER_STORAGE","ohos.permission.WRITE_USER_STORAGE"} ,2);
            }
        }catch(Exception ex){}
        ResourceManager resManager = getResourceManager();
        try
        {
            Dialog_Title = resManager.getElement(ResourceTable.String_Dialog_Title).getString();
            Dialog_Content_StoragePermissionFailed = resManager.getElement(ResourceTable.String_Dialog_Content_StoragePermissionFailed).getString();
            Dialog_Content_CameraPermissionFailed = resManager.getElement(ResourceTable.String_Dialog_Content_CameraPermissionFailed).getString();
            Dialog_Button_Cancel = resManager.getElement(ResourceTable.String_Dialog_Button_Cancel).getString();
            Dialog_Button_Confirm = resManager.getElement(ResourceTable.String_Dialog_Button_Confirm).getString();
            Toast_NoneName = resManager.getElement(ResourceTable.String_ThemeToast_NoneName).getString();
            Toast_NoneDesigner = resManager.getElement(ResourceTable.String_ThemeToast_NoneDesigner).getString();
            Toast_NoneVersion = resManager.getElement(ResourceTable.String_ThemeToast_NoneVersion).getString();
            Toast_NoneBriefInfo = resManager.getElement(ResourceTable.String_ThemeToast_NoneBriefInfo).getString();
            Toast_NoneDesktop = resManager.getElement(ResourceTable.String_ThemeToast_NoneDesktop).getString();
            Toast_NoneUnlock = resManager.getElement(ResourceTable.String_ThemeToast_NoneUnlock).getString();
            Toast_NoneBackground = resManager.getElement(ResourceTable.String_ThemeToast_NoneBackground).getString();
            Toast_IsProcessing = resManager.getElement(ResourceTable.String_ThemeToast_IsProcessing).getString();
            Toast_Theme_SaveFinish = resManager.getElement(ResourceTable.String_ThemeToast_SaveFinish).getString();
            Toast_Theme_SaveFailed = resManager.getElement(ResourceTable.String_ThemeToast_SaveFailed).getString();
        }catch (Exception e){}
        isProcessing = false;
        textBox_ChineseName = (TextField) findComponentById(ResourceTable.Id_textBox_chineseName);
        textBox_InternationalName = (TextField) findComponentById(ResourceTable.Id_textBox_internationalName);
        textBox_DesignerName = (TextField) findComponentById(ResourceTable.Id_textBox_designerName);
        textBox_VersionCode = (TextField) findComponentById(ResourceTable.Id_textBox_versionCode);
        textBox_BriefInfo = (TextField) findComponentById(ResourceTable.Id_textBox_briefInfo);
        TextBoxManager.TextBoxForStyle(this,textBox_ChineseName);
        TextBoxManager.TextBoxForStyle(this,textBox_InternationalName);
        TextBoxManager.TextBoxForStyle(this,textBox_DesignerName);
        TextBoxManager.TextBoxForStyle(this,textBox_VersionCode);
        TextBoxManager.TextBoxForStyle(this,textBox_BriefInfo);
        DatabaseManager.Init(this);
        textBox_ChineseName.setText(DatabaseManager.getString("SpeedUpTheme_ChineseName"));
        textBox_InternationalName.setText(DatabaseManager.getString("SpeedUpTheme_InternationalName"));
        textBox_DesignerName.setText(DatabaseManager.getString("SpeedUpTheme_DesignerName"));
        textBox_VersionCode.setText(DatabaseManager.getString("SpeedUpTheme_VersionCode"));
        textBox_BriefInfo.setText(DatabaseManager.getString("SpeedUpTheme_BriefInfo"));
        textBox_ChineseName.addTextObserver((s, i, i1, i2) ->
        {
            try
            {
                textBox_ChineseName.setText(TextManager.removeSpecificCharArray(textBox_ChineseName.getText()));
                DatabaseManager.Init(this);
                DatabaseManager.setString("SpeedUpTheme_ChineseName",textBox_ChineseName.getText());
            }
            catch (Exception e){}
        });
        textBox_InternationalName.addTextObserver((s, i, i1, i2) ->
        {
            try
            {
                textBox_InternationalName.setText(TextManager.removeSpecificCharArray(textBox_InternationalName.getText()));
                DatabaseManager.Init(this);
                DatabaseManager.setString("SpeedUpTheme_InternationalName",textBox_InternationalName.getText());
            }
            catch (Exception e){}
        });
        textBox_DesignerName.addTextObserver((s, i, i1, i2) ->
        {
            try
            {
                textBox_DesignerName.setText(TextManager.removeSpecificCharArray(textBox_DesignerName.getText()));
                DatabaseManager.Init(this);
                DatabaseManager.setString("SpeedUpTheme_DesignerName",textBox_DesignerName.getText());
            }
            catch (Exception e){}
        });
        textBox_VersionCode.addTextObserver((s, i, i1, i2) ->
        {
            try
            {
                String VersionCodeText = "";
                char[] texts = textBox_VersionCode.getText().toCharArray();
                char last = '?';
                for(int o=0;o<texts.length;o++)
                {
                    if(TextManager.isNumChar(texts[o]))
                    {
                        if(texts[o]!=last||texts[o]!='.')
                        {
                            VersionCodeText += texts[o];
                            last = texts[o];
                        }
                    }
                }
                if(VersionCodeText.startsWith("."))
                {
                    VersionCodeText = "12"+VersionCodeText;
                }else if(VersionCodeText.startsWith("0"))
                {
                    VersionCodeText = "12";
                }else if(VersionCodeText.startsWith("0.")||VersionCodeText.startsWith("1.")||VersionCodeText.startsWith("2.")||VersionCodeText.startsWith("3.")||VersionCodeText.startsWith("4.")||VersionCodeText.startsWith("5.")||VersionCodeText.startsWith("6.")||VersionCodeText.startsWith("7.")||VersionCodeText.startsWith("8.")||VersionCodeText.startsWith("9.")||VersionCodeText.startsWith("10.")||VersionCodeText.startsWith("11."))
                {
                    VersionCodeText = "12"+VersionCodeText.substring(VersionCodeText.indexOf('.'));
                }
                textBox_VersionCode.setText(VersionCodeText);
                DatabaseManager.Init(this);
                DatabaseManager.setString("SpeedUpTheme_VersionCode",VersionCodeText);
            }
            catch (Exception e){}
        });
        textBox_BriefInfo.addTextObserver((s, i, i1, i2) ->
        {
            try
            {
                textBox_BriefInfo.setText(TextManager.removeSpecificCharArray(textBox_BriefInfo.getText()));
                DatabaseManager.Init(this);
                DatabaseManager.setString("SpeedUpTheme_BriefInfo",textBox_BriefInfo.getText());
            }
            catch (Exception e){}
        });
        text_ChineseName = findComponentById(ResourceTable.Id_text_chineseName);
        text_InternationalName = findComponentById(ResourceTable.Id_text_internationalName);
        text_DesignerName = findComponentById(ResourceTable.Id_text_designerName);
        text_VersionCode = findComponentById(ResourceTable.Id_text_versionCode);
        DisplayAttributes displayAttributes = DisplayManager.getInstance().getDefaultDisplay(this).get().getAttributes();
        int maxTextWidth = displayAttributes.width-(int)(216f*displayAttributes.scalDensity+0.5f);
        text_ChineseName.setLayoutRefreshedListener(c->{if(c.getWidth()>maxTextWidth)c.setWidth(maxTextWidth);});
        text_InternationalName.setLayoutRefreshedListener(c->{if(c.getWidth()>maxTextWidth)c.setWidth(maxTextWidth);});
        text_DesignerName.setLayoutRefreshedListener(c->{if(c.getWidth()>maxTextWidth)c.setWidth(maxTextWidth);});
        text_VersionCode.setLayoutRefreshedListener(c->{if(c.getWidth()>maxTextWidth)c.setWidth(maxTextWidth);});
        DatabaseManager.Init(this);
        Color01 = DatabaseManager.getString("SpeedUpTheme_Color01","FFC6B7");
        Color02 = DatabaseManager.getString("SpeedUpTheme_Color02","FCE4DE");
        Color03 = DatabaseManager.getString("SpeedUpTheme_Color03","F4C4B7");
        Color04 = DatabaseManager.getString("SpeedUpTheme_Color04","FF8362");
        Color05 = DatabaseManager.getString("SpeedUpTheme_Color05","FFC1B0");
        Color06 = DatabaseManager.getString("SpeedUpTheme_Color06","996D61");
        Color07 = DatabaseManager.getString("SpeedUpTheme_Color07","FF8362");
        Color08 = DatabaseManager.getString("SpeedUpTheme_Color08","FCD8CF");
        Color09 = DatabaseManager.getString("SpeedUpTheme_Color09","FFF4F2");
        Color10 = DatabaseManager.getString("SpeedUpTheme_Color10","F4EDEB");
        Color11 = DatabaseManager.getString("SpeedUpTheme_Color11","EA791A");
        Color12 = DatabaseManager.getString("SpeedUpTheme_Color12","CCFFF6F4");
        Color13 = DatabaseManager.getString("SpeedUpTheme_Color13","E17618");
        Color14 = DatabaseManager.getString("SpeedUpTheme_Color14","FFEEEA");
        Color15 = DatabaseManager.getString("SpeedUpTheme_Color15","FCDCD4");
        Color16 = DatabaseManager.getString("SpeedUpTheme_Color16","FFF2EF");
        Color17 = DatabaseManager.getString("SpeedUpTheme_Color17","FCDED6");
        Color18 = DatabaseManager.getString("SpeedUpTheme_Color18","FFDCD3");
        Color19 = DatabaseManager.getString("SpeedUpTheme_Color19","E2907A");
        text_ColorSelector = (Text) findComponentById(ResourceTable.Id_colorBox_mainColor);
        text_ColorSelector.setText("#"+Color04);
        text_ColorSelector.setClickedListener(c ->
        {
            if(!isProcessing)
            {
                if(colorDialog==null)
                    showDialog_ColorSelector();
                else
                {
                    if(!colorDialog.isDestroyed)
                    {
                        colorDialog.setDestroyedListener(null);
                        colorDialog.destory();
                    }
                    colorDialog = null;
                    System.gc();
                    showDialog_ColorSelector();
                }
            }else
                new GeneralToast(this).setText(Toast_IsProcessing).show();
        });
        text_DesktopSelector = (Text) findComponentById(ResourceTable.Id_emptyBox_desktopSelector);
        text_DesktopSelector.setText("Desktop.jpg");
        text_DesktopSelector.setClickedListener(c ->
        {
            if(!isProcessing)
            {
                try
                {
                    DisplayAttributes attributes = DisplayManager.getInstance().getDefaultDisplay(this).get().getAttributes();
                    imageSelector_Popup = new PopupDialog(getContext(), c);
                    Component layout = LayoutScatter.getInstance(getContext()).parse(ResourceTable.Layout_popup_image_selector, null, false);

                    DirectionalLayout directionalLayout = (DirectionalLayout) layout.findComponentById(ResourceTable.Id_root_container);
                    directionalLayout.setBackground(new ShapeElement(){{setRgbColor(RgbColor.fromArgbInt(ResourceTool.getColor(getContext(),ResourceTable.Color_dawnlighti_button_normal,Color.getIntColor("#FFFFFF"))));setCornerRadius((int)((20f*attributes.scalDensity)+0.5f));}});
                    Image DocumentMode = (Image) layout.findComponentById(ResourceTable.Id_Doc_Selector);
                    Image CameraMode = (Image) layout.findComponentById(ResourceTable.Id_Cam_Selector);
                    DocumentMode.setClickedListener(cc->
                    {
                        try
                        {
                            if (verifySelfPermission("ohos.permission.READ_USER_STORAGE") != IBundleManager.PERMISSION_GRANTED || verifySelfPermission("ohos.permission.WRITE_USER_STORAGE") != IBundleManager.PERMISSION_GRANTED)
                                showPermissionRequest();
                            else
                                selectPic(ChooseImage_Desktop);
                        }catch(Exception ex){}
                        try {imageSelector_Popup.destroy();imageSelector_Popup=null;}catch (Exception ex){}
                    });
                    CameraMode.setClickedListener(cc->
                    {
                        try
                        {
                            if (verifySelfPermission("ohos.permission.CAMERA") != IBundleManager.PERMISSION_GRANTED)
                                showPermissionRequest_Camera();
                            else
                                selectPic_byCamera(ChooseImage_Desktop_byCamera);
                        }catch(Exception ex){}
                        try {imageSelector_Popup.destroy();imageSelector_Popup=null;}catch (Exception ex){}
                    });
                    imageSelector_Popup.setTransparent(true);
                    imageSelector_Popup.setCustomComponent(layout);
                    imageSelector_Popup.setMode(LayoutAlignment.TOP|LayoutAlignment.HORIZONTAL_CENTER);
                    imageSelector_Popup.setCornerRadius((int)((24f*attributes.scalDensity)+0.5f));
                    imageSelector_Popup.setAutoClosable(true);
                    imageSelector_Popup.show();
                }catch(Exception ex){ex.printStackTrace();}
            }else
                new GeneralToast(this).setText(Toast_IsProcessing).show();
        });
        text_UnlockSelector = (Text) findComponentById(ResourceTable.Id_emptyBox_unlockSelector);
        text_UnlockSelector.setText("Unlock.jpg");
        text_UnlockSelector.setClickedListener(c ->
        {
            if(!isProcessing)
            {
                try
                {
                    DisplayAttributes attributes = DisplayManager.getInstance().getDefaultDisplay(this).get().getAttributes();
                    imageSelector_Popup = new PopupDialog(getContext(), c);
                    Component layout = LayoutScatter.getInstance(getContext()).parse(ResourceTable.Layout_popup_image_selector, null, false);

                    DirectionalLayout directionalLayout = (DirectionalLayout) layout.findComponentById(ResourceTable.Id_root_container);
                    directionalLayout.setBackground(new ShapeElement(){{setRgbColor(RgbColor.fromArgbInt(ResourceTool.getColor(getContext(),ResourceTable.Color_dawnlighti_button_normal,Color.getIntColor("#FFFFFF"))));setCornerRadius((int)((20f*attributes.scalDensity)+0.5f));}});
                    Image DocumentMode = (Image) layout.findComponentById(ResourceTable.Id_Doc_Selector);
                    Image CameraMode = (Image) layout.findComponentById(ResourceTable.Id_Cam_Selector);
                    DocumentMode.setClickedListener(cc->
                    {
                        try
                        {
                            if (verifySelfPermission("ohos.permission.READ_USER_STORAGE") != IBundleManager.PERMISSION_GRANTED || verifySelfPermission("ohos.permission.WRITE_USER_STORAGE") != IBundleManager.PERMISSION_GRANTED)
                                showPermissionRequest();
                            else
                                selectPic(ChooseImage_Unlock);
                        }catch(Exception ex){}
                        try {imageSelector_Popup.destroy();imageSelector_Popup=null;}catch (Exception ex){}
                    });
                    CameraMode.setClickedListener(cc->
                    {
                        try
                        {
                            if (verifySelfPermission("ohos.permission.CAMERA") != IBundleManager.PERMISSION_GRANTED)
                                showPermissionRequest_Camera();
                            else
                                selectPic_byCamera(ChooseImage_Unlock_byCamera);
                        }catch(Exception ex){}
                        try {imageSelector_Popup.destroy();imageSelector_Popup=null;}catch (Exception ex){}
                    });
                    imageSelector_Popup.setTransparent(true);
                    imageSelector_Popup.setCustomComponent(layout);
                    imageSelector_Popup.setMode(LayoutAlignment.TOP|LayoutAlignment.HORIZONTAL_CENTER);
                    imageSelector_Popup.setCornerRadius((int)((24f*attributes.scalDensity)+0.5f));
                    imageSelector_Popup.setAutoClosable(true);
                    imageSelector_Popup.show();
                }catch(Exception ex){}
            }else
                new GeneralToast(this).setText(Toast_IsProcessing).show();
        });
        text_CardRadius = (Text) findComponentById(ResourceTable.Id_text_cardRadius);
        RadiusSlider = (Slider) findComponentById(ResourceTable.Id_slider_cardRadius);
        RadiusSlider.setMinValue(12);
        RadiusSlider.setMaxValue(32);
        DatabaseManager.Init(getContext());
        int R_value = DatabaseManager.getInt("ServiceCardCornerRadiusValue",16);
        RadiusSlider.setProgressValue(R_value);
        text_CardRadius.setText(ResourceTool.getString(getContext(),ResourceTable.String_SimpleInfo_Card,"卡片圆角（[值]元量）").replaceFirst("\\[值\\]",String.valueOf(R_value)));
        RadiusSlider.setStep(2);
        RadiusSlider.setValueChangedListener(new Slider.ValueChangedListener()
        {
            @Override
            public void onProgressUpdated(Slider slider, int i, boolean b)
            {
                DatabaseManager.Init(getContext());
                DatabaseManager.setInt("ServiceCardCornerRadiusValue",i);
                text_CardRadius.setText(ResourceTool.getString(getContext(),ResourceTable.String_SimpleInfo_Card,"卡片圆角（[值]元量）").replaceFirst("\\[值\\]",String.valueOf(i)));
            }

            @Override
            public void onTouchStart(Slider slider) {}
            @Override
            public void onTouchEnd(Slider slider) {}
        });
        pxm = GeneralUtil.getPixelMapFromResource(this,ResourceTable.Media_AddPicturesArea);
        showImageArea = (Image) findComponentById(ResourceTable.Id_showImageArea);
        showImageArea.setPixelMap(pxm);
        showImageArea.setCornerRadius(12f*displayAttributes.scalDensity);
        showImageArea.setClickedListener(c ->
        {
            if(!isProcessing)
            {
                try
                {
                    if (verifySelfPermission("ohos.permission.READ_USER_STORAGE") != IBundleManager.PERMISSION_GRANTED || verifySelfPermission("ohos.permission.WRITE_USER_STORAGE") != IBundleManager.PERMISSION_GRANTED)
                        showPermissionRequest();
                    else
                        selectPic(ChooseImage_Background);
                }catch(Exception ex){}
            }else
                new GeneralToast(this).setText(Toast_IsProcessing).show();
        });
        Button Button_StartProcess= (Button) findComponentById(ResourceTable.Id_Button_StartProcess);
        int spacingHorizontal = (int) ResourceTool.getFloat(this, ResourceTable.Float_spacing_ui_button, 0);
        Button_StartProcess.setBackground(new GeneralButtonElement(this, GeneralButtonElement.TYPE_UI_Button));
        Button_StartProcess.setTextColor(new Color(ResourceTool.getColor(this, ResourceTable.Color_dawnlighti_button_text_accent, 0xFFFFFF)));
        Button_StartProcess.setMultipleLine(false);
        Button_StartProcess.setTruncationMode(Text.TruncationMode.ELLIPSIS_AT_END);
        Button_StartProcess.setPaddingLeft(spacingHorizontal);
        Button_StartProcess.setPaddingRight(spacingHorizontal);
        Button_StartProcess.setClickedListener(c->
        {
            try
            {
                if(showImageArea.getPixelMap()!=null&&showImageArea.getPixelMap()!=pxm)
                {
                    if(!isProcessing)
                    {
                        if(verifySelfPermission("ohos.permission.READ_USER_STORAGE") != IBundleManager.PERMISSION_GRANTED || verifySelfPermission("ohos.permission.WRITE_USER_STORAGE") != IBundleManager.PERMISSION_GRANTED)
                            showPermissionRequest();
                        else if(text_DesktopSelector.getText().equals("Desktop.jpg")||!new File(getCacheDir() + "/SpeedUpTheme/Desktop.jpg").exists())
                        {
                            text_DesktopSelector.setText("Desktop.jpg");
                            new GeneralToast(this).setText(Toast_NoneDesktop).show();
                        }
                        else if(text_UnlockSelector.getText().equals("Unlock.jpg")||!new File(getCacheDir() + "/SpeedUpTheme/Unlock.jpg").exists())
                        {
                            text_UnlockSelector.setText("Unlock.jpg");
                            new GeneralToast(this).setText(Toast_NoneUnlock).show();
                        }
                        else if(textBox_ChineseName.getText().equals("")&&textBox_InternationalName.getText().equals(""))
                            new GeneralToast(this).setText(Toast_NoneName).show();
                        else if(textBox_DesignerName.getText().equals(""))
                            new GeneralToast(this).setText(Toast_NoneDesigner).show();
                        else if(textBox_VersionCode.getText().equals(""))
                            new GeneralToast(this).setText(Toast_NoneVersion).show();
                        else if(textBox_BriefInfo.getText().equals(""))
                            new GeneralToast(this).setText(Toast_NoneBriefInfo).show();
                        else if(!PreloadServiceAbility.isSuccess)
                        {
                            try
                            {
                                Intent e = new Intent();
                                //通过Intent中的OperationBuilder类构造operation对象，指定设备标识（空串表示当前设备）、应用包名、Ability名称
                                Operation operation = new Intent.OperationBuilder()
                                        .withBundleName("com.agger.harmonyosthemeseditor")
                                        .withAbilityName("com.agger.harmonyosthemeseditor.abilities.PreloadServiceAbility")
                                        .build();
                                // 把operation设置到intent中
                                e.setOperation(operation);
                                startAbility(e);
                            }catch (Exception ex){}
                            new GeneralToast(this).setText(ResourceTool.getString(this,ResourceTable.String_ThemeToast_EnvironmentNotReady,"智慧意识未就绪，请确保必要支持库已成功部署！")).show();
                        }else
                        {
                            isProcessing = true;
                            textBox_ChineseName.setEnabled(false);
                            textBox_InternationalName.setEnabled(false);
                            textBox_DesignerName.setEnabled(false);
                            textBox_VersionCode.setEnabled(false);
                            textBox_BriefInfo.setEnabled(false);
                            RadiusSlider.setEnabled(false);
                            textBox_ChineseName.setClickedListener(i->new GeneralToast(this).setText(Toast_IsProcessing).show());
                            textBox_InternationalName.setClickedListener(i->new GeneralToast(this).setText(Toast_IsProcessing).show());
                            textBox_DesignerName.setClickedListener(i->new GeneralToast(this).setText(Toast_IsProcessing).show());
                            textBox_VersionCode.setClickedListener(i->new GeneralToast(this).setText(Toast_IsProcessing).show());
                            textBox_BriefInfo.setClickedListener(i->new GeneralToast(this).setText(Toast_IsProcessing).show());
                            if(textBox_ChineseName.getText().equals("")) textBox_ChineseName.setText(textBox_InternationalName.getText());
                            else if(textBox_InternationalName.getText().equals("")) textBox_InternationalName.setText(textBox_ChineseName.getText());
                            String ThemeVersion = textBox_VersionCode.getText();
                            if(!ThemeVersion.contains("."))
                            {
                                ThemeVersion += ".0";
                            }else if(ThemeVersion.endsWith("."))
                            {
                                ThemeVersion += "0";
                            }
                            if(ThemeVersion.startsWith("0.")||ThemeVersion.startsWith("1.")||ThemeVersion.startsWith("2.")||ThemeVersion.startsWith("3.")||ThemeVersion.startsWith("4.")||ThemeVersion.startsWith("5.")||ThemeVersion.startsWith("6.")||ThemeVersion.startsWith("7.")||ThemeVersion.startsWith("8.")||ThemeVersion.startsWith("9.")||ThemeVersion.startsWith("10.")||ThemeVersion.startsWith("11."))
                            {
                                ThemeVersion = "12"+ThemeVersion.substring(ThemeVersion.indexOf('.'));
                            }
                            textBox_VersionCode.setText(ThemeVersion);
                            screenEventHandler.sendSyncEvent(1,EventHandler.Priority.IMMEDIATE);
                            PacThemeEventHandler.sendEvent(0, 0, EventHandler.Priority.IMMEDIATE);
                        }
                    }else
                    {
                        new GeneralToast(this).setText(Toast_IsProcessing).show();
                    }
                }else
                {
                    new GeneralToast(this).setText(Toast_NoneBackground).show();
                }
            }catch(Exception e){}
        });
        findComponentById(ResourceTable.Id_actionBar_Back).setClickedListener(c->onBackPressed());
        DatabaseManager.Init(this);
        String Ability_QuitBySelf = DatabaseManager.getString("SpeedUpThemeAbility_QuitBySelf","No");
        if(!Ability_QuitBySelf.equals("Yes"))
        {
            File DesktopFile = new File(getCacheDir() + "/SpeedUpTheme/Desktop.jpg");
            if(!DesktopFile.exists())
            {
                String UriString = DatabaseManager.getString("SpeedUpThemeAbility_ImageUri_Desktop","None");
                if(!UriString.equals("None"))
                {
                    Uri uri_rec =Uri.parse(UriString);
                    PixelMap pixelMap_rec = ImageIntelligent.ObtainImage(uri_rec,this);
                    if(pixelMap_rec != null)
                    {
                        ImageIntelligent.saveImage(getCacheDir() + "/SpeedUpTheme/Desktop.jpg",pixelMap_rec);
                        if(DesktopFile.exists())text_DesktopSelector.setText(ResourceTool.getString(getContext(),ResourceTable.String_SimpleInfo_ImageModified,"*已设置"));
                    }
                }
            }else
                text_DesktopSelector.setText(ResourceTool.getString(getContext(),ResourceTable.String_SimpleInfo_ImageModified,"*已设置"));
            File UnlockFile = new File(getCacheDir() + "/SpeedUpTheme/Unlock.jpg");
            if(!UnlockFile.exists())
            {
                String UriString = DatabaseManager.getString("SpeedUpThemeAbility_ImageUri_Unlock","None");
                if(!UriString.equals("None"))
                {
                    Uri uri_rec =Uri.parse(UriString);
                    PixelMap pixelMap_rec = ImageIntelligent.ObtainImage(uri_rec,this);
                    if(pixelMap_rec != null)
                    {
                        ImageIntelligent.saveImage(getCacheDir() + "/SpeedUpTheme/Unlock.jpg",pixelMap_rec);
                        if(UnlockFile.exists())text_UnlockSelector.setText(ResourceTool.getString(getContext(),ResourceTable.String_SimpleInfo_ImageModified,"*已设置"));
                    }
                }
            }else
                text_UnlockSelector.setText(ResourceTool.getString(getContext(),ResourceTable.String_SimpleInfo_ImageModified,"*已设置"));
            File BgImageFile = new File(getCacheDir() + "/SpeedUpTheme/Background.jpg");
            if(BgImageFile.exists())
            {
                PixelMap pixelMap_rec = GeneralUtil.getPixelMapFromFile(BgImageFile);
                if(pixelMap_rec != null) showImageArea.setPixelMap(pixelMap_rec);
            }
            else
            {
                String UriString = DatabaseManager.getString("SpeedUpThemeAbility_ImageUri_Background","None");
                if(!UriString.equals("None"))
                {
                    Uri uri_rec =Uri.parse(UriString);
                    PixelMap pixelMap_rec = ImageIntelligent.ObtainImage(uri_rec,this);
                    if(pixelMap_rec != null)
                    {
                        ImageIntelligent.saveImage(getCacheDir() + "/SpeedUpTheme/Background.jpg",pixelMap_rec);
                        showImageArea.setPixelMap(pixelMap_rec);
                    }
                }
            }
        }
        DatabaseManager.setString("SpeedUpThemeAbility_QuitBySelf","No");
        PacThemeEventHandler = new PacThemeEventHandler(EventRunner.create(true));
    }

    @Override
    public void onBackPressed()
    {
        if(!isProcessing)
        {
            DatabaseManager.Init(this);
            DatabaseManager.setString("LastAbilityName","None");
            DatabaseManager.setString("SpeedUpThemeAbility_QuitBySelf","Yes");
            DatabaseManager.setString("SpeedUpThemeAbility_ImageUri_Background", "None");
            DatabaseManager.setString("SpeedUpThemeAbility_ImageUri_Desktop", "None");
            DatabaseManager.setString("SpeedUpThemeAbility_ImageUri_Unlock", "None");
            DatabaseManager.setString("SpeedUpThemeAbility_VideoUri", "None");
            try{getWindow().setNavigationBarColor(ResourceTool.getColor(this, ResourceTable.Color_dawnlighti_navigationbar_bottom, 0xF5F1E6));}catch (Exception ex){}
            ThemesEditorAbility.isMainSceneSlice = true;
            try{showImageArea.release();}catch(Exception e){}
            try{pxm.release();}catch(Exception e){}
            try{textBox_ChineseName.release();}catch(Exception e){}
            try{textBox_InternationalName.release();}catch(Exception e){}
            try{textBox_DesignerName.release();}catch(Exception e){}
            try{textBox_VersionCode.release();}catch(Exception e){}
            try{textBox_BriefInfo.release();}catch(Exception e){}
            try{text_ChineseName.release();}catch(Exception e){}
            try{text_InternationalName.release();}catch(Exception e){}
            try{text_DesignerName.release();}catch(Exception e){}
            try{text_VersionCode.release();}catch(Exception e){}
            try{text_ColorSelector.release();}catch(Exception e){}
            try{text_DesktopSelector.release();}catch(Exception e){}
            try{text_UnlockSelector.release();}catch(Exception e){}
            try{text_CardRadius.release();}catch(Exception e){}
            try{RadiusSlider.release();}catch(Exception e){}
            showImageArea=null;
            pxm = null;
            textBox_ChineseName = null;
            textBox_InternationalName = null;
            textBox_DesignerName = null;
            textBox_VersionCode = null;
            textBox_BriefInfo = null;
            text_ChineseName = null;
            text_InternationalName = null;
            text_DesignerName = null;
            text_VersionCode = null;
            Dialog_Title = null;
            Dialog_Content_StoragePermissionFailed = null;
            Dialog_Content_CameraPermissionFailed = null;
            Dialog_Button_Cancel = null;
            Dialog_Button_Confirm = null;
            Toast_NoneName = null;
            Toast_NoneDesigner = null;
            Toast_NoneVersion = null;
            Toast_NoneBriefInfo = null;
            Toast_NoneBackground = null;
            Toast_IsProcessing = null;
            Toast_Theme_SaveFinish = null;
            Toast_Theme_SaveFailed = null;
            mainThreadEventHandler = null;
            PacThemeEventHandler = null;
            screenEventHandler = null;
            text_ColorSelector = null;
            text_DesktopSelector = null;
            text_UnlockSelector = null;
            text_CardRadius = null;
            RadiusSlider = null;
            Color01 = null;
            Color02 = null;
            Color03 = null;
            Color04 = null;
            Color05 = null;
            Color06 = null;
            Color07 = null;
            Color08 = null;
            Color09 = null;
            Color10 = null;
            Color11 = null;
            Color12 = null;
            Color13 = null;
            Color14 = null;
            Color15 = null;
            Color16 = null;
            Color17 = null;
            Color18 = null;
            Color19 = null;
            System.gc();
            if(ThemesEditorAbility.LayoutChanged)
            {
                ThemesEditorAbility.LayoutChanged = false;
                try{MainSceneSlice.Instance.restart();}catch (Exception ex){}
            }
            else
            {
                try{MainSceneSlice.Instance.pageSwiper.ReturnImageSwiper_Industry(true);}catch (Exception ex){}
            }
            super.onBackPressed();
        }else
        {
            new GeneralToast(this).setText(Toast_IsProcessing).show();
        }
    }

    private CommonDialog.DestroyedListener colorSelectorListener()
    {
        return () ->
        {
            DatabaseManager.Init(this);
            Color04 = ColorManager.getColorHex(colorDialog.getColorValue());
            try{text_ColorSelector.setText("#"+Color04);}catch (Exception ex){}
            DatabaseManager.setString("SpeedUpTheme_Color04",Color04);
            ColorManager.HsvBox hsvBox = colorDialog.getHsvBox();
            float H = hsvBox.getHue();
            float S = hsvBox.getSaturation();
            float V = hsvBox.getValue();
            Color01 = ColorManager.getColorHex(HsvColor.toColor(255,H, 28f, 100f));
            Color02 = ColorManager.getColorHex(HsvColor.toColor(255,H,12f, 99f));
            Color03 = ColorManager.getColorHex(HsvColor.toColor(255,H,25f, 96f));
            Color05 = ColorManager.getColorHex(HsvColor.toColor(255,H, (100f-S)*0.8f, 100f));
            Color06 = ColorManager.getColorHex(HsvColor.toColor(255,H, 36f, 60f));
            Color07 = Color04;
            Color08 = ColorManager.getColorHex(HsvColor.toColor(255,H,18f, 99f));
            Color09 = ColorManager.getColorHex(HsvColor.toColor(255,H, 5f, 100f));
            Color10 = ColorManager.getColorHex(HsvColor.toColor(255,H, 4f, 96f));
            Color11 = ColorManager.getColorHex(HsvColor.toColor(255,H, S, V*0.92f));
            Color12 = ColorManager.getColorHex(HsvColor.toColor(255,H, 4f, 100f));
            Color13 = ColorManager.getColorHex(HsvColor.toColor(255,H, S, V*0.9f));
            Color14 = ColorManager.getColorHex(HsvColor.toColor(255,H, 8f, 100f));
            Color15 = ColorManager.getColorHex(HsvColor.toColor(255,H, 16f,99f));
            Color16 = ColorManager.getColorHex(HsvColor.toColor(255,H, 6f, 100f));
            Color17 = ColorManager.getColorHex(HsvColor.toColor(255,H, 15f, 99f));
            Color18 = ColorManager.getColorHex(HsvColor.toColor(255,H, 17f, 100f));
            Color19 = ColorManager.getColorHex(HsvColor.toColor(255,H, 46f,89f));
            DatabaseManager.setString("SpeedUpTheme_Color01",Color01);
            DatabaseManager.setString("SpeedUpTheme_Color02",Color02);
            DatabaseManager.setString("SpeedUpTheme_Color03",Color03);
            DatabaseManager.setString("SpeedUpTheme_Color05",Color05);
            DatabaseManager.setString("SpeedUpTheme_Color06",Color06);
            DatabaseManager.setString("SpeedUpTheme_Color07",Color07);
            DatabaseManager.setString("SpeedUpTheme_Color08",Color08);
            DatabaseManager.setString("SpeedUpTheme_Color09",Color09);
            DatabaseManager.setString("SpeedUpTheme_Color10",Color10);
            DatabaseManager.setString("SpeedUpTheme_Color11",Color11);
            DatabaseManager.setString("SpeedUpTheme_Color12",Color12);
            DatabaseManager.setString("SpeedUpTheme_Color13",Color13);
            DatabaseManager.setString("SpeedUpTheme_Color14",Color14);
            DatabaseManager.setString("SpeedUpTheme_Color15",Color15);
            DatabaseManager.setString("SpeedUpTheme_Color16",Color16);
            DatabaseManager.setString("SpeedUpTheme_Color17",Color17);
            DatabaseManager.setString("SpeedUpTheme_Color18",Color18);
            DatabaseManager.setString("SpeedUpTheme_Color19",Color19);
        };
    }

    private void showDialog_ColorSelector()
    {
        colorDialog = new ColorDialog(this);
        colorDialog.setDestroyedListener(colorSelectorListener());
        colorDialog
                .setTitle(ResourceTool.getString(this,ResourceTable.String_Dialog_SelectorColor,"选择颜色"))
                .setCloseText(ResourceTool.getString(this,ResourceTable.String_Dialog_text_close,"关闭"))
                .setDefaultColor(text_ColorSelector.getText())
                .setOutsideTouchClosable(false)
                .show();
    }

    private void recoverDialog_ColorSelector()
    {
        DatabaseManager.Init(getContext());
        colorDialog = new ColorDialog(this);
        colorDialog.setDestroyedListener(colorSelectorListener());
        colorDialog
                .setTitle(ResourceTool.getString(this,ResourceTable.String_Dialog_SelectorColor,"选择颜色"))
                .setCloseText(ResourceTool.getString(this,ResourceTable.String_Dialog_text_close,"关闭"))
                .setDefaultColor(DatabaseManager.getInt("ColorDialog_TempColorValue",-1))
                .setOutsideTouchClosable(false)
                .show();
    }

    public void PermissionRouter(GeneralDialog dialog)
    {
        Intent e = new Intent();
        Operation operation = new Intent.OperationBuilder()
                .withAction(IntentConstants.ACTION_APPLICATION_DETAILS_SETTINGS)
                .withUri(Uri.getUriFromParts("package",getBundleName(),null))
                .build();
        e.setOperation(operation);
        startAbility(e);
        dialog.remove();
    }

    private void showPermissionRequest()
    {
        if (canRequestPermission("ohos.permission.READ_USER_STORAGE") && canRequestPermission("ohos.permission.WRITE_USER_STORAGE"))
            requestPermissionsFromUser(new String[]{"ohos.permission.READ_USER_STORAGE", "ohos.permission.WRITE_USER_STORAGE"}, 2);
        else
        {
            GeneralDialog.Builder builder = new GeneralDialog.Builder(getContext());
            builder.setTitle(Dialog_Title)
                    .setContent(Dialog_Content_StoragePermissionFailed)
                    .addButton(Dialog_Button_Cancel, GeneralButtonElement.TYPE_NORMAL, GeneralDialog::remove)
                    .addButton(Dialog_Button_Confirm, GeneralButtonElement.TYPE_ACCENT, this::PermissionRouter)
                    .setOutsideTouchClosable(false)
                    .setMovable(false)
                    .create()
                    .show();
        }
    }

    private void showPermissionRequest_Camera()
    {
        if (canRequestPermission("ohos.permission.CAMERA"))
            requestPermissionsFromUser(new String[]{"ohos.permission.CAMERA"}, 1);
        else
        {
            GeneralDialog.Builder builder = new GeneralDialog.Builder(getContext());
            builder.setTitle(Dialog_Title)
                    .setContent(Dialog_Content_CameraPermissionFailed)
                    .addButton(Dialog_Button_Cancel, GeneralButtonElement.TYPE_NORMAL, GeneralDialog::remove)
                    .addButton(Dialog_Button_Confirm, GeneralButtonElement.TYPE_ACCENT, this::PermissionRouter)
                    .setOutsideTouchClosable(false)
                    .setMovable(false)
                    .create()
                    .show();
        }
    }

    private void updateXmlColorValue(String fileName)
    {
        File xmlFile = new File(fileName);
        try
        {
            FileInputStream in = new FileInputStream(xmlFile);
            byte[] b = new byte[(int) xmlFile.length()];
            in.read(b);
            String xmlText = new String(b);
            in.close();
            DatabaseManager.Init(getContext());
            xmlText = xmlText.replaceAll("\\*【01】旧版顶部栏配色\\*",Color01);
            xmlText = xmlText.replaceAll("\\*【02】导航栏配色\\*",Color02);
            xmlText = xmlText.replaceAll("\\*【03】中等深度标签普通配色\\*",Color03);
            xmlText = xmlText.replaceAll("\\*【04】主题核心配色\\*", Color04);
            xmlText = xmlText.replaceAll("\\*【05】主要浅色高亮配色\\*",Color05);
            xmlText = xmlText.replaceAll("\\*【06】搜索框文字配色\\*",Color06);
            xmlText = xmlText.replaceAll("\\*【07】主要顶部图示配色\\*",Color07);
            xmlText = xmlText.replaceAll("\\*【08】柔浅小贴士背景\\*",Color08);
            xmlText = xmlText.replaceAll("\\*【09】圆形按钮底色\\*",Color09);
            xmlText = xmlText.replaceAll("\\*【10】圆形按钮按压色\\*",Color10);
            xmlText = xmlText.replaceAll("\\*【11】圆形按钮图示色\\*",Color11);
            xmlText = xmlText.replaceAll("\\*【12】开关栏背景配色(含透明度)\\*",Color12);
            xmlText = xmlText.replaceAll("\\*【13】主用较深按压色\\*",Color13);
            xmlText = xmlText.replaceAll("\\*【14】对话框底板配色\\*",Color14);
            xmlText = xmlText.replaceAll("\\*【15】拨号器键盘底色\\*",Color15);
            xmlText = xmlText.replaceAll("\\*【16】程式背景浅底色\\*",Color16);
            xmlText = xmlText.replaceAll("\\*【17】邮件搜索框及侧边色\\*",Color17);
            xmlText = xmlText.replaceAll("\\*【18】短信顶部底部配色\\*",Color18);
            xmlText = xmlText.replaceAll("\\*【19】旧版状态栏开关色\\*",Color19);
            FileOutputStream out = null;
            try
            {
                out = new FileOutputStream(xmlFile);
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, StandardCharsets.UTF_8));
                writer.write(xmlText);
                writer.close();
                out.flush();
                out.close();
            }catch(IOException ex){ex.printStackTrace();}
            finally
            {
                try
                {
                    if (out != null)
                    {
                        out.close();
                    }
                } catch(IOException e){}
            }
        }catch(IOException ex) {}
    }

    private void updateXmlRadiusValue(String fileName)
    {
        File xmlFile = new File(fileName);
        try
        {
            FileInputStream in = new FileInputStream(xmlFile);
            byte[] b = new byte[(int) xmlFile.length()];
            in.read(b);
            String xmlText = new String(b);
            in.close();
            DatabaseManager.Init(getContext());
            xmlText = xmlText.replaceAll("16dp",DatabaseManager.getInt("ServiceCardCornerRadiusValue",16)+"dp");
            FileOutputStream out = null;
            try
            {
                out = new FileOutputStream(xmlFile);
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, StandardCharsets.UTF_8));
                writer.write(xmlText);
                writer.close();
                out.flush();
                out.close();
            }catch(IOException ex){ex.printStackTrace();}
            finally
            {
                try
                {
                    if (out != null)
                    {
                        out.close();
                    }
                } catch(IOException e){}
            }
        }catch(IOException ex) {}
    }

    private void selectPic(int fileMode)
    {
        Intent intent = new Intent();
        Operation opt=new Intent.OperationBuilder()
                .withAction("android.intent.action.OPEN_DOCUMENT")
                .withFlags(Intent.FLAG_NOT_OHOS_COMPONENT)
                .build();
        intent.setOperation(opt);
        intent.setType("image/*");
        startAbilityForResult(intent,fileMode);
    }

    private void selectPic_byCamera(int fileMode)
    {
        String workPath = getCacheDir() + "/SpeedUpTheme";
        if(!new File(workPath).exists())new File(workPath).mkdirs();
        Intent e = new Intent();
        Operation operation = new Intent.OperationBuilder()
                .withBundleName("com.agger.harmonyosthemeseditor")
                .withAbilityName("com.agger.harmonyosthemeseditor.abilities.TakePhotoAbility")
                .build();
        e.setOperation(operation);
        e.setParam("output",workPath+(fileMode==ChooseImage_Desktop_byCamera?"/Desktop.jpg":"/Unlock.jpg"));
        if((text_DesktopSelector.getText().equals("Desktop.jpg"))&&(new File(getCacheDir()+"/SpeedUpTheme/Desktop.jpg").exists())) FileManager.deleteFile(getCacheDir()+"/SpeedUpTheme/Desktop.jpg");
        if((text_UnlockSelector.getText().equals("Unlock.jpg"))&&(new File(getCacheDir()+"/SpeedUpTheme/Unlock.jpg").exists())) FileManager.deleteFile(getCacheDir()+"/SpeedUpTheme/Unlock.jpg");
        startAbilityForResult(e,fileMode);
    }

    private void selectVideo(String fileMode)
    {
        Intent intent = new Intent();
        Operation opt=new Intent.OperationBuilder()
                .withAction("android.intent.action.OPEN_DOCUMENT")
                .withFlags(Intent.FLAG_NOT_OHOS_COMPONENT)
                .build();
        intent.setOperation(opt);
        intent.setType("video/mp4");
        startAbilityForResult(intent,ChooseVideo);
    }

    @Override
    protected void onAbilityResult(int requestCode, int resultCode, Intent resultData)
    {
        if (requestCode == ChooseImage_Desktop_byCamera)
        {
            try
            {
                if(new File(getCacheDir()+"/SpeedUpTheme/Desktop.jpg").exists())
                {
                    text_DesktopSelector.setText(ResourceTool.getString(getContext(),ResourceTable.String_SimpleInfo_ImageModified,"*已设置"));
                }
            }catch (Exception e){}
        }
        else if (requestCode == ChooseImage_Unlock_byCamera)
        {
            try
            {
                if(new File(getCacheDir()+"/SpeedUpTheme/Unlock.jpg").exists())
                {
                    text_UnlockSelector.setText(ResourceTool.getString(getContext(),ResourceTable.String_SimpleInfo_ImageModified,"*已设置"));
                }
            }catch (Exception e){}
        }
        else if(requestCode==ChooseImage_Background)
        {
            //放入尝试体内，防止用户未选择图片而造成应用闪退
            try
            {
                String ImageUri=resultData.getUriString();
                Uri targetUri;
                DatabaseManager.Init(this);
                if(ImageUri.contains("externalstorage"))
                {
                    targetUri = resultData.getUri();
                    DatabaseManager.setString("SpeedUpThemeAbility_ImageUri_Background", ImageUri);
                }else
                {
                    String ImageId;
                    if(ImageUri.lastIndexOf("%3A")!=-1)ImageId = ImageUri.substring(ImageUri.lastIndexOf("%3A")+3);
                    else ImageId = ImageUri.substring(ImageUri.lastIndexOf('/')+1);
                    targetUri=Uri.appendEncodedPathToUri(AVStorage.Images.Media.EXTERNAL_DATA_ABILITY_URI,ImageId);
                    DatabaseManager.setString("SpeedUpThemeAbility_ImageUri_Background",targetUri.toString());
                }
                DataAbilityHelper dataAbilityHelper = GeneralUtil.createDataAbilityHelper(this);
                ImageSource imageSource = null;
                try
                {
                    FileDescriptor fd = dataAbilityHelper.openFile(targetUri, "r");
                    imageSource = ImageSource.create(fd, null);
                    PixelMap pixelMap = imageSource.createPixelmap(null);
                    String workPath = getCacheDir() + "/SpeedUpTheme";
                    if(!new File(workPath).exists())new File(workPath).mkdirs();
                    ImageIntelligent.saveImage(workPath+"/Background.jpg",pixelMap);
                    if(new File(workPath+"/Background.jpg").exists())
                    {
                        int maxQuality = GeneralUtil.getMaxQuality(getContext());
                        showImageArea.setPixelMap(Math.max(pixelMap.getImageInfo().size.width,pixelMap.getImageInfo().size.height)>maxQuality?ImageIntelligent.ResizeImage(pixelMap,maxQuality):pixelMap);
                        if(ImageIntelligent.isDarkImage(pixelMap))
                            new GeneralToast(getContext()).setText(ResourceTool.getString(getContext(),ResourceTable.String_IToast_BackgroundTooDark,"智慧助手：请注意，侦测到所选图片的色彩较为暗淡，以此作为程序背景，或将严重破坏主题的体验效果！")).show();
                    }
                } catch (Exception e) {} finally {if(imageSource!=null)imageSource.release();}
            }catch (Exception e){}
        }else if(requestCode==ChooseImage_Desktop)
        {
            //放入尝试体内，防止用户未选择图片而造成应用闪退
            try
            {
                String ImageUri=resultData.getUriString();
                Uri targetUri;
                DatabaseManager.Init(this);
                if(ImageUri.contains("externalstorage"))
                {
                    targetUri = resultData.getUri();
                    DatabaseManager.setString("SpeedUpThemeAbility_ImageUri_Desktop", ImageUri);
                }else
                {
                    String ImageId;
                    if(ImageUri.lastIndexOf("%3A")!=-1)ImageId = ImageUri.substring(ImageUri.lastIndexOf("%3A")+3);
                    else ImageId = ImageUri.substring(ImageUri.lastIndexOf('/')+1);
                    targetUri=Uri.appendEncodedPathToUri(AVStorage.Images.Media.EXTERNAL_DATA_ABILITY_URI,ImageId);
                    DatabaseManager.setString("SpeedUpThemeAbility_ImageUri_Desktop",targetUri.toString());
                }
                DataAbilityHelper dataAbilityHelper = GeneralUtil.createDataAbilityHelper(this);
                ImageSource imageSource = null;
                try
                {
                    FileDescriptor fd = dataAbilityHelper.openFile(targetUri, "r");
                    imageSource = ImageSource.create(fd, null);
                    PixelMap pixelMap = imageSource.createPixelmap(null);
                    String workPath = getCacheDir() + "/SpeedUpTheme";
                    if(!new File(workPath).exists())new File(workPath).mkdirs();
                    ImageIntelligent.saveImage(workPath+"/Desktop.jpg",pixelMap);
                    if(new File(workPath+"/Desktop.jpg").exists())
                    {
                        text_DesktopSelector.setText(ResourceTool.getString(getContext(),ResourceTable.String_SimpleInfo_ImageModified,"*已设置"));
                    }
                } catch (Exception e) {} finally {if(imageSource!=null)imageSource.release();}
            }catch (Exception e){}
        }else if(requestCode==ChooseImage_Unlock)
        {
            //放入尝试体内，防止用户未选择图片而造成应用闪退
            try
            {
                String ImageUri=resultData.getUriString();
                Uri targetUri;
                DatabaseManager.Init(this);
                if(ImageUri.contains("externalstorage"))
                {
                    targetUri = resultData.getUri();
                    DatabaseManager.setString("SpeedUpThemeAbility_ImageUri_Unlock", ImageUri);
                }else
                {
                    String ImageId;
                    if(ImageUri.lastIndexOf("%3A")!=-1)ImageId = ImageUri.substring(ImageUri.lastIndexOf("%3A")+3);
                    else ImageId = ImageUri.substring(ImageUri.lastIndexOf('/')+1);
                    targetUri=Uri.appendEncodedPathToUri(AVStorage.Images.Media.EXTERNAL_DATA_ABILITY_URI,ImageId);
                    DatabaseManager.setString("SpeedUpThemeAbility_ImageUri_Unlock",targetUri.toString());
                }
                DataAbilityHelper dataAbilityHelper = GeneralUtil.createDataAbilityHelper(this);
                ImageSource imageSource = null;
                try
                {
                    FileDescriptor fd = dataAbilityHelper.openFile(targetUri, "r");
                    imageSource = ImageSource.create(fd, null);
                    PixelMap pixelMap = imageSource.createPixelmap(null);
                    String workPath = getCacheDir() + "/SpeedUpTheme";
                    if(!new File(workPath).exists())new File(workPath).mkdirs();
                    ImageIntelligent.saveImage(workPath+"/Unlock.jpg",pixelMap);
                    if(new File(workPath+"/Unlock.jpg").exists())
                    {
                        text_UnlockSelector.setText(ResourceTool.getString(getContext(),ResourceTable.String_SimpleInfo_ImageModified,"*已设置"));
                    }
                } catch (Exception e) {} finally {if(imageSource!=null)imageSource.release();}
            }catch (Exception e){}
        }
        else if(requestCode==ChooseVideo)
        {
            //放入尝试体内，防止用户未选择图片而造成应用闪退
            try
            {
                String VideoUri=resultData.getUriString();
                Uri targetUri;
                if(VideoUri.contains("externalstorage"))
                {
                    targetUri = resultData.getUri();
                }else
                {
                    String VideoId;
                    if(VideoUri.lastIndexOf("%3A")!=-1)VideoId = VideoUri.substring(VideoUri.lastIndexOf("%3A")+3);
                    else VideoId = VideoUri.substring(VideoUri.lastIndexOf('/')+1);
                    targetUri=Uri.appendEncodedPathToUri(AVStorage.Video.Media.EXTERNAL_DATA_ABILITY_URI,VideoId);
                }
                DataAbilityHelper dataAbilityHelper = GeneralUtil.createDataAbilityHelper(this);
                try
                {
                    FileDescriptor fd = dataAbilityHelper.openFile(targetUri, "r");
                    if(FileManager.getFileSize(fd)>80*1048576)
                    {
                        new GeneralToast(this).setText(ResourceTool.getString(this,ResourceTable.String_ThemeToast_VideoTooLarge,"文件过大，请选择80MB以内的视频！")).show();
                    }else
                    {
                        DatabaseManager.Init(this);
                        DatabaseManager.setString("SpeedUpThemeAbility_VideoUri",targetUri.toString());
                        AVMetadataHelper avMetadataHelper = new AVMetadataHelper ();
                        avMetadataHelper.setSource(fd);
                        Player player = new Player(this);
                        Source source = new Source(fd);
                        player.setSource(source);
                        player.prepare();
                        int totalTime = player.getDuration();
                        PixelMap pixelMap =  avMetadataHelper.fetchVideoPixelMapByTime((long)(totalTime*0.3f), 0x00);
                        showImageArea.setPixelMap(pixelMap);
                        InputStream inputStream = null;
                        OutputStream outputStream = null;
                        try
                        {
                            //必须重新获取FileDescriptor，否则文件会因为前置操作而残缺不可用
                            inputStream = new FileInputStream(dataAbilityHelper.openFile(targetUri, "r"));
                            outputStream = new FileOutputStream(getCacheDir()+"/target.mp4");
                            byte[] buffer = new byte[1024];
                            int length;
                            while ((length=inputStream.read(buffer))>0)
                            {
                                outputStream.write(buffer,0,length);
                            }
                            outputStream.flush();
                            outputStream.close();
                        }finally
                        {
                            try
                            {
                                if (outputStream != null)
                                    outputStream.close();
                                if(inputStream != null)
                                    inputStream.close();
                            } catch(IOException e){}
                        }
                    }
                } catch (Exception e) {new GeneralToast(this).setText(e.getMessage()).show();} finally {}
            }catch (Exception e){}
        }
    }

    @Override
    public void onActive() {super.onActive();}

    @Override
    public void onForeground(Intent intent) {super.onForeground(intent);}
}